import React, { useRef, useState } from 'react';
import Generator, {
  defaultCommonSettings,
  defaultGlobalSettings,
  // defaultSettings,
} from 'fr-generator';
import './less.less';
import { defaultSettings } from './setting';
import InputIcon from '../../assets/Form/Input.png';
import module from '../../assets/Form/module.png';
import moduleChecked from '../../assets/Form/moduleChecked.png';
import outlineTree from '../../assets/Form/outlineTree.png';
import outlineTreeChecked from '../../assets/Form/outlineTreeChecked.png';
import history from '../../assets/Form/history.png';
import historyChecked from '../../assets/Form/historyChecked.png';
import logo from '../../assets/logo.png';
import { Tabs, Row, Col, Button, Modal, Input, message, Form } from 'antd';

const { TextArea } = Input;
const { Provider, Sidebar, Canvas, Settings } = Generator;

const defaultValue = {
  type: 'object',
  properties: {
    inputName: {
      title: '简单输入框',
      type: 'string',
    },
  },
};

const FormDesign = ({ saveFormSchema, schema, settingItem }: any) => {
  // 绑定表单设计器
  const genRef = useRef();
  // 绑定导入表单
  const [importForm] = Form.useForm();
  // 左侧tab栏选中项key
  const [tabsKey, setTabKey] = useState<string>('1');
  // 导出的JSON对象
  const [schemaString, setSchemaString] = useState<string>('');
  // 控制导出弹框
  const [isExportModalOpen, setIsExportModalOpen] = useState(false);
  // 控制导入弹框
  const [isImportModalOpen, setIsImportExportModalOpen] = useState(false);
  //
  const [formPreview, setFormPreview] = useState(false);

  // 控制预览状态
  const previewForm = () => {
    setFormPreview((o) => !o);
  };

  // 点击保存表单设计
  const saveSchema = () => {
    let schemas = genRef.current?.getValue();
    let schemaString = JSON.stringify(schemas, null, 2);
    // console.log(schemaString);

    saveFormSchema(schemaString);
  };
  // 点击清空表单设计
  const emptySchema = () => {
    genRef.current?.setValue({
      labelWidth: 120,
      displayType: 'row',
    });
  };

  // 点击导入按钮
  const importSchema = () => {
    setIsImportExportModalOpen(true);
  };

  // 点击导入弹框确定
  const handleImportOk = () => {
    // 获取输入内容
    let value = importForm.getFieldValue('importSchemaString');
    // JSON字符串转对象
    let schemaObj = JSON.parse(value);
    // 修改设计器值
    genRef.current?.setValue(schemaObj);
    // 关闭导入弹框
    setIsImportExportModalOpen(false);
  };

  // 点击导入弹框取消
  const handleImportCancel = () => {
    setIsImportExportModalOpen(false);
  };

  // 点击导出按钮
  const exportSchema = () => {
    let schemas = genRef.current?.getValue();
    let schemaString = JSON.stringify(schemas, null, 2);
    setSchemaString(schemaString);
    setIsExportModalOpen(true);
  };

  // 导出框复制按钮
  const handleExportOk = () => {
    navigator.clipboard.writeText(schemaString);
    message.success('已复制表单配置到剪切板');
    setIsExportModalOpen(false);
  };

  // 导出框取消按钮
  const handleExportCancel = () => {
    setIsExportModalOpen(false);
  };

  // 左侧tab栏切换
  const onChange = (key: string) => {
    setTabKey(key);
  };

  const fromFlowable = (schemas: any) => {
    if (schemas['#']) {
      return schemas;
    }

    let arr = schema?.fields || [];
    let obj = {
      type: 'object',
      properties: {},
    };
    if (arr[0]) {
      obj = {
        type: 'object',
        column: arr[0].params.column,
        displayType: arr[0].params.displayType,
        labelWidth: arr[0].params.labelWidth,
        properties: {},
      };
    }
    for (let i = 0; i < arr.length; i++) {
      const item = arr[i];
      obj.properties[item.id] = item.params;
    }
    return obj;
  };

  const toFlowable = (schemas: any) => {
    let flowableSchema = {
      name: settingItem.name,
      key: settingItem.key,
      fields: [],
    };
    for (const key in schemas.properties) {
      let item = schemas.properties[key];
      let obj = {
        type: 'text',
        name: item.title,
        required: item.required,
        readOnly: item.readOnly,
        id: key,
        overrideId: true,
        placeholder: item.placeholder,
        params: {
          ...item,
          minLength: item.minLength,
          maxLength: item.maxLength,
        },
      };
      if (item.type == 'string') {
        switch (item.format) {
          case 'textarea':
            obj.type = 'multi-line-text';
            break;
          case 'date':
            obj.type = 'date';
            break;
        }
        switch (item.widget) {
          case 'select':
            obj.type = 'dropdown';
            obj.fieldType = 'OptionFormField';
            break;
          case 'radio':
            obj.type = 'radio-buttons';
            obj.fieldType = 'OptionFormField';
            break;
          default:
            break;
        }
        if (item.widget == 'dropdown' || item.widget == 'radio') {
          obj.options = [];
          for (const key in item.enumNames) {
            let obj2 = {
              name: item.enumNames[key],
              id: item.enum[key],
            };
            obj.options.push(obj2);
          }
        }
      } else if (item.type == 'number') {
        obj.type = 'integer';
      }
      flowableSchema.fields.push(obj);
    }
    if (flowableSchema.fields[0]) {
      flowableSchema.fields[0].params = {
        ...flowableSchema.fields[0].params,
        column: schemas.column,
        displayType: schemas.displayType,
        labelWidth: schemas.labelWidth,
      };
    }
    if (formPreview) {
      return schemas;
    }
    return flowableSchema;
  };

  return (
    <div className="wrap">
      <div className="heard">
        <Row>
          <Col flex="200px">
            <div className="logo">
              <img src={logo} width={40} height={40} />
              <div className="logoTitle">bsin-form</div>
            </div>
          </Col>
          <Col flex="auto" style={{ textAlign: 'right', lineHeight: '64px' }}>
            <Button onClick={emptySchema} style={{ margin: '0 0 0 20px' }}>
              清空表单
            </Button>
            <Button onClick={importSchema} style={{ margin: '0 0 0 20px' }}>
              导入schema
            </Button>
            <Button onClick={exportSchema} style={{ margin: '0 20px 0 20px' }}>
              导出schema
            </Button>
            <Button onClick={previewForm}>
              {formPreview ? '返回编辑' : '预览效果'}
            </Button>
            <Button
              onClick={saveSchema}
              style={{ margin: '0 60px 0 20px' }}
              type="primary"
            >
              保存表单
            </Button>
          </Col>
        </Row>
        {/* 导入弹框 */}
        <Modal
          title="导入schema"
          open={isImportModalOpen}
          okText="确定"
          onOk={handleImportOk}
          onCancel={handleImportCancel}
        >
          <Form form={importForm}>
            <Form.Item name="importSchemaString">
              <TextArea rows={15} />
            </Form.Item>
          </Form>
        </Modal>
        {/* 导出弹框 */}
        <Modal
          title="导出schema"
          open={isExportModalOpen}
          okText="复制"
          onOk={handleExportOk}
          onCancel={handleExportCancel}
        >
          <TextArea rows={15} value={schemaString} />
        </Modal>
      </div>
      <Tabs
        tabPosition="left"
        tabBarGutter={0}
        onChange={onChange}
        size="small"
        items={[
          {
            label: (
              <img
                src={tabsKey == '1' ? moduleChecked : module}
                width={20}
                height={20}
              />
            ),
            key: '1',
            children: (
              <div style={{ height: 'calc(100vh - 66px)' }}>
                <Generator
                  ref={genRef}
                  preview={formPreview}
                  defaultValue={schema}
                  extraButtons={[false, false, false, false]}
                  settings={defaultSettings}
                  transformer={{
                    from: fromFlowable,
                    to: toFlowable,
                  }}
                />
              </div>
            ),
          },
          {
            label: (
              <img
                src={tabsKey == '2' ? outlineTreeChecked : outlineTree}
                width={20}
                height={20}
              />
            ),
            key: '2',
            children: `Content of Tab Pane 2`,
          },
          {
            label: (
              <img
                src={tabsKey == '3' ? historyChecked : history}
                width={20}
                height={20}
              />
            ),
            key: '3',
            children: `Content of Tab Pane 3`,
          },
        ]}
      />
    </div>
  );
};

export default FormDesign;
